package com.koudai.reader;

import java.util.Iterator;
import java.util.List;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.ListView;
import android.widget.RelativeLayout;

import com.koudai.reader.android.R;
import com.koudai.reader.conponment.ExistDialog;
import com.koudai.reader.conponment.ListViewAdapter;
import com.koudai.reader.util.HttpUtils;
import com.koudai.reader.vo.Book;
import com.koudai.reader.vo.EndUser;

public class TopBookListActivity extends Activity implements OnScrollListener {

    public static ScheduledExecutorService threadPool = Executors.newScheduledThreadPool(1);
    private ListView bookList;
    private ListViewAdapter mListViewAdapter;

    private RelativeLayout mLoadLayout;
    private RelativeLayout mLoadFailedlayout;

    private int mLastItem = 0;
    private int mCount = 50;
    private LayoutInflater maininflater;

    private int categoryid = 0;
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);

        setContentView(R.layout.book_list);
        categoryid = getIntent().getIntExtra("sort_type", 0);

        
        bookList = (ListView) findViewById(R.id.book_list);
        mListViewAdapter = new ListViewAdapter(this, internalhandler);

        maininflater = (LayoutInflater) getSystemService(LAYOUT_INFLATER_SERVICE);

        mLoadLayout = (RelativeLayout) maininflater.inflate(R.layout.loadpage, null);

        mLoadLayout.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                threadPool.schedule(new AppListHttpRequest(), 100, TimeUnit.MILLISECONDS);
            }
        });

        mLoadFailedlayout = (RelativeLayout) maininflater.inflate(R.layout.load_failed_page, null);

        mLoadFailedlayout.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                bookList.removeFooterView(mLoadFailedlayout);
                bookList.addFooterView(mLoadLayout);
                threadPool.schedule(new AppListHttpRequest(), 100, TimeUnit.MILLISECONDS);
            }
        });
        bookList.addFooterView(mLoadLayout);
        bookList.setAdapter(mListViewAdapter);
        bookList.setOnScrollListener(this);

    }

    public void onScroll(AbsListView view, int mFirstVisibleItem, int mVisibleItemCount, int mTotalItemCount) {

        mLastItem = mFirstVisibleItem + mVisibleItemCount - 1;

        if (mListViewAdapter.count >= mCount) {
            bookList.removeFooterView(mLoadLayout);
        }

    }

    public void onScrollStateChanged(AbsListView view, int mScrollState) {
        // **
        // 当ListView滑动到最后一条记录时这时，我们会看到已经被添加到ListView的"加载项"布局， 这时应该加载剩余数据。

        if (mLastItem == mListViewAdapter.count && mScrollState == OnScrollListener.SCROLL_STATE_IDLE) {
            if (mListViewAdapter.count <= mCount) {
                threadPool.schedule(new AppListHttpRequest(), 100, TimeUnit.MILLISECONDS);
            }
        }

    }

    

    class AppListHttpRequest implements Runnable {

        @Override
        public void run() {

            try {
                final List<Book> bookData = HttpUtils.searchTop(categoryid);

                internalhandler.post(new Runnable() {

                    @Override
                    public void run() {
                        Iterator<Book> iterator = bookData.iterator();

                        mListViewAdapter.count = 0;
                        while (iterator.hasNext()) {
                            Book book = iterator.next();
                            mListViewAdapter.bookDataList.put(mListViewAdapter.count++, book);
                        }

                        bookList.removeFooterView(mLoadLayout);
                        mListViewAdapter.notifyDataSetChanged();
                    }
                });
            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
                sendMsg(100);
            }
        }
    }

    private void sendMsg(int flag) {
        Message msg = new Message();
        msg.what = flag;
        internalhandler.sendMessage(msg);
    }

    private Handler internalhandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            // 定义一个Handler，用于处理下载线程与UI间通讯
            if (!Thread.currentThread().isInterrupted()) {
                switch (msg.what) {

                case 100:
                    // app list 加载失败
                    bookList.removeFooterView(mLoadLayout);
                    bookList.addFooterView(mLoadFailedlayout);
                    break;
                case 1:
                    //更新积分
                    if (TopBookListActivity.this.getParent() instanceof BookCityActivity) {
                       ((BookCityActivity) TopBookListActivity.this.getParent()).score.setText(EndUser.getInstance().getGlodStr());
                    }
                }
            }
            super.handleMessage(msg);
        }
    };

    protected void onResume() {
        super.onResume();
        threadPool.schedule(new AppListHttpRequest(), 0, TimeUnit.MILLISECONDS);
    };

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (event.getKeyCode() == KeyEvent.KEYCODE_BACK) {
            if (event.getAction() == KeyEvent.ACTION_DOWN && event.getRepeatCount() == 0) {
                ExistDialog.showDialog(this.getParent() == null ? this : this.getParent());
                return true;
            }
        }

        return super.onKeyDown(keyCode, event);
    }
}
